import {Component, OnInit, Renderer2} from '@angular/core';
import {ApiService} from '@core/services/http/api.service';
import {agCurrency, deepClone} from '../../../utils/utils';
import {ApesMessageService} from "@shared/apes/message";
import {GridConfigService} from "@core/config/grid-config.service";
import {GridOptions} from '@ag-grid-community/core';;
import {ExportExcelService} from "@core/services/excel/export-excel.service";
import {AllModules,Module} from "@ag-grid-enterprise/all-modules";
import {ExpressionService} from "@core/services/expression/ExpressionService";

@Component({
  selector: 'balance-sheet',
  templateUrl: './balance-sheet-form.component.html',
  // styleUrls: ['./balance-sheet-form.component.scss']
})

// tslint:disable-next-line:class-name
export class balanceSheetFormComponent implements OnInit {
  /** grid 相关 **/
  modules:Module[]=AllModules;
  rowData: any[] = [];
  columnDefsMeteData: any[];
  columnDefsItemMeteData: any[];
  columnDefs: any = [];
  gridOptions: GridOptions;
  // height: any = 500 + 'px';
  tabList: any = [];
  ctx = {model: {}};
  localeText: any;

  /** 按钮相关 **/
  buttonBar = [
    {hide: true, style: 'default', label: '查询', id: 'action_query', loading: false},
    {hide: true, style: 'default', label: '下载', id: 'action_export'}
  ];

  hidn: string = 'none';            // 脑袋必填项
  company: any[];
  companyId: string = null;
  yearId: number = null;
  monthId: number = null;
  year = [];
  month = [];

  /**关联跳转**/
  relevancyMetadata;

  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private renderer: Renderer2,
              private exportExcelService: ExportExcelService,
              protected expressionService: ExpressionService,
              private gridConfigService: GridConfigService) {
    this.columnDefsMeteData = [
      {
        headerName: "资产",
        field: "ass",
        width: 180,
        sortable: false
      },
      {
        headerName: "行次",
        field: "assSeq",
        width: 80,
        sortable: false
      },
      {
        headerName: "年初余额",
        field: "openingBalance",
        width: 125,
        valueFormatter: "currency",
        sortable: false
      },
      {
        headerName: "期末余额",
        field: "endingBalance",
        width: 135,
        valueFormatter: "currency",
        sortable: false
      },
      {
        headerName: "负债和所有者权益",
        field: "liabilityEquity",
        width: 240,
        sortable: false
      },
      {
        headerName: "行次",
        field: "liabilityEquitySeq",
        width: 80,
        sortable: false
      },
      {
        headerName: "年初余额",
        field: "liabilityOpeningBalance",
        width: 125,
        valueFormatter: "currency",
        sortable: false
      },
      {
        headerName: "期末余额",
        field: "liabilityEndingBalance",
        width: 135,
        valueFormatter: "currency",
        sortable: false
      },
    ];
    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 100,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
  }

  ngOnInit() {

    this.relevancyMetadata = {
      links: [
        { link: { title: '财务明细账', id: 'financial/detailSheet/detailSheetFormComponent' } },
        // { link: { title: '财务总分类帐', id: 'financial/generalLedger/generalLedgerFormComponent' } },
        { link: { title: '财务科目余额表', id: 'financial/accountBalance/accountBalanceFormComponent' } },
        { link: { title: '应收应付账龄分析', id: 'report/fa.agingAnalyse.query' } },
        { link: { title: '资产负债表', id: 'financial/balanceSheet/balanceSheetFormComponent' } },
        { link: { title: '利润表', id: 'financial/incomeStatement/incomeStatementFormComponent' } },
        { link: { title: '现金流量表', id: 'financial/cashflowStatement/cashflowStatementFormComponent' } },
      ],
    };

    this.columnDefs = deepClone(this.columnDefsMeteData);
    this.columnDefs.forEach(col =>{
      if (col.valueFormatter =='currency'){
        col.valueFormatter = agCurrency;
      }
    })
    let iLength = this.columnDefs.length;
    this.tabList = [];
    for (let i = 0; i < iLength; i++) {
      this.dynamicTab(this.columnDefs[i]);
    }

    this.columnDefsMeteData;
    this.getCompany();
    this.getYear();
    this.getMonth();
  }

  customSearchFn(term: string, item:any) {
    term = term.toLowerCase();
    return item.name.toLowerCase().indexOf(term) > -1 || item.id.toLowerCase().indexOf(term) > -1;
  }

  ngAfterViewInit() {
    // 获取 container 元素
    let content = document.querySelector('.content');
    let contentHeight = content[ 'clientHeight' ];
    let apesGrid = document.querySelector('.ag-theme-balham');
    setTimeout(() => {
      let apesBox = document.querySelector('.boxShowFlex');
      let apesBoxHeight = apesBox.clientHeight;
      this.renderer.setStyle(apesGrid, 'height', (contentHeight - apesBoxHeight - 67) + 'px');
    }, 100);
  }

  // 导出数据
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, '资产负债报表');
  }
  dynamicTab(item: any) {
    let tab = {
      id: item.id,
      title: item.name,
      columnDefs: this.columnDefsItemMeteData
    }
    this.tabList.push(tab);
    // this.tabsId = this.tabList[0].id;
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.action_query();
      }else if (data.id === 'action_export') {
        this.action_export();
      }
    }
  }

  /** 主数据 查询按钮事件 **/
  action_query() {
    if (this.companyId === null || this.yearId === null || this.monthId === null) {
      this.msg.info("请输入查询条件！");
      this.hidn = 'block';
    } else {
      this.hidn = 'none';
      this.getTableFieldData();
    }
    this.buttonBar[0].loading = false;
  }


  // /** 点击tab页签触发的事件 **/
  // tabChanges(tabId: any) {
  //   this.currentPage = 1;
  //   this.tabsId = tabId;
  // }

  /** 日期转换 **/
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  /** 主表数据 **/
  getTableFieldData() {
    let data = {'company': this.companyId, 'year': this.yearId, 'month': this.monthId};
    this.apiService.post('finance.balanceSheet.find', {'body': JSON.stringify(data)}).subscribe(data => {
      if (data) {
        this.rowData = data;
        if (this.rowData.length === 0) {
          this.msg.info(`未找到满足条件的数据`);
        }
      } else {
        this.msg.info(data.msg);
      }
    })
  }


  /** 获取 公司 **/
  getCompany() {
    let data = {'pages': 1, 'size': 5000};
    this.apiService.post('cm.company.fin.find', {'body': JSON.stringify(data)}).subscribe(
      (body) => {
        if (body) {
          this.company = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  test() {
    // console.log(this.companyId);
    this.getYear();

  }

  invokmonth() {
    this.getMonth();
  }

  // /** 获取 会计年度 **/
  getYear() {
    let data = {'year': 0, 'company': this.companyId};
    if (this.companyId != null) {
      this.apiService.post('finance.accountingPeriod.fiscalPeriod', {'body': JSON.stringify(data)}).subscribe(
        (body) => {
          if (body) {
            this.year = body.year;
          } else {
            this.msg.info(body.msg);
          }
        });
    }
  }

  /** 获取 会计月份 **/
  getMonth() {
    if (this.companyId != null) {
      let data = {'year': this.yearId, 'company': this.companyId};
      this.apiService.post('finance.accountingPeriod.fiscalPeriod', {'body': JSON.stringify(data)}).subscribe(
        (body) => {
          if (body) {
            this.month = body.month;
          } else {
            this.msg.info(body.msg);
          }
        });
    }
  }

  /** 保留两位小数点 **/
  toFixed(params) {
    let key = params.colDef.field;
    let data = params.data[key];
    if (data !== undefined) {
      data = data.toFixed(2);
    }
    return data;
  }


  // 时间转换 7.5小时算天（配合导出使用）
  showTime(data) {
    let a = data >= 0 ? '' : '-';
    data = data >= 0 ? data : -data;

    let day = Math.floor(data / 450);
    let hour = day >= 0
      ? Math.floor((data - (day * 450) ) / 60)
      :Math.floor(data / 60);
    let minute = hour >= 0
      ? Math.floor(data - (day * 450) - (hour * 60) )
      : data < 0
        ? data
        : Math.floor(data / 60 / 7.5);

    let time = "";
    if ( day > 0 ) {
      time = a +  day + "天" + hour + "小时" + minute + "分钟";
    }else if( hour ){
      time = a +  hour + "小时" + minute + "分钟";
    }else if( minute ){
      time = a +  minute + "分钟";
    }
    return time;
  }

  getValueFormatter(): string {
    return '\'[\' +value.id+ \']\' + \' \' + value.name';
  }
  getDownFormatter(): string {
    return '\'[\' +value.id+ \']\' + \' \' + value.name';
  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      value: value
    });
  }
}

